package cn.yzx.pethome.jwt;

import cn.yzx.pethome.utils.JwtUtils;
import cn.yzx.pethome.utils.RsaUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

//登录上下文，把登录的相关信息放到这里面，方便调用
// 问题1：不受spring管理的类，想要获取受spring管理的bean 只要获取到spring容器就可以从容器中获取
@Slf4j
public class LoginContextUtils {

    /**
     *
     * @param request
     * @return 如果是后台需要返回employee，如果是前台返回user
     */
    public static Object getLoginUser(HttpServletRequest request){
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token))
            return null;
        //获取公钥
        PublicKey publicKey = RsaUtils.getPublicKey(JwtRasHolder.INSTANCE.getJwtRsaPubData());
        //通过公钥解析token，登陆载荷体
        Payload<PayloadData> payload = JwtUtils.getInfoFromToken(token, publicKey, PayloadData.class);
        PayloadData payloadData = payload.getUserInfo();
        if (payloadData==null){
            log.error("payloadData is null!");
            return null;
        }
        return payloadData.getUser()!=null?payloadData.getUser():payloadData.getAdmin();
    }
}